// pages/private-space/video-detail/public-video/advertising/ad.ts
import { addADV, queryADVByPage, delADV, modifyADV, getADV } from '../../../api/index'
import { upload } from '../../../utils/upload'
import Toast from '@vant/weapp/toast/toast';
import dayjs from '../../../utils/dayjs'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    adList: [],
    checkAdLink: "",
    isShowAddLink: false,
    // 新增广告
    adLink: "",//广告链接
    adSlogan: "",//广告描述
    chatHeight: 0,
    adPicList: [] as { url: string }[],
    adType: '1',
    focusId: "",
    pageOption: {
      "Name": "",
      "PageOptions": {
        "PageIndex": 1,
        "PageSize": 9999,
        "Total": 0
      }
    },
    searchName: "",
    editId: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    if (e.ADVId != 'undefined') {
      this.setData({
        checkAdLink: e.ADVId
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onCheckChange(event) {
    this.setData({
      checkAdLink: event.detail
    })
  },
  toggleCheck(event) {
    const { value } = event.currentTarget.dataset;
    if (value == this.data.checkAdLink) {
      this.setData({
        checkAdLink: "",
      });
    } else {
      this.setData({
        checkAdLink: value
      });
    }
  },
  openAddLink() {
    this.setData({
      isShowAddLink: true
    });
  },
  onClickAddPopOverlay() {
    this.setData({
      isShowAddLink: false
    })
  },
  // input框聚焦
  keyboardheightchange(e) {
    this.setData({
      chatHeight: e.detail.height
    })
  },
  inputTap(e) {
    const { name } = e.currentTarget.dataset;
    wx.hideKeyboard()
    setTimeout(() => {
      this.setData({
        focusId: name
      })
    }, 300);
  },
  setNextInput() {
    this.setData({
      focusId: 'adLink'
    })
  },
  // 弹出框确认按钮事件
  onAddPopConfirm() {
    if (this.data.adPicList.length <= 0) {
      Toast.fail("请上传广告图标")
      return
    }
    if (this.data.adSlogan == "") {
      Toast.fail("请填写广告语")
      return
    }
    if (this.data.adLink == "") {
      Toast.fail("请填写广告链接")
      return
    }
    const adParams = {
      "Name": this.data.adSlogan,
      "ADVType": Number(this.data.adType),
      "ADVUrl": this.data.adLink,
      "StartTime": dayjs(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss'),
      "EndTime": dayjs(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss'),
      "Disable": 0,
      "CoverUrl": this.data.adPicList[0].url,
      "HitNum": 0
    }
    if (this.data.editId) {
      modifyADV(Object.assign(adParams, { Id: this.data.editId })).then(res => {
        this.setData({
          isShowAddLink: false
        });
        this.onAddPopClose();
        this.getData()
      })
    } else {
      addADV(adParams).then(res => {
        console.log(res);
        this.setData({
          isShowAddLink: false
        });
        this.onAddPopClose();
        this.getData();
      })
    }
  },
  // 弹出框取消按钮事件
  onAddPopCancel() {
    this.setData({
      isShowAddLink: false,
    });
    this.onAddPopClose()
  },
  // 弹出框关闭触发
  onAddPopClose() {
    this.setData({
      adSlogan: "",
      adLink: "",
      adPicList: [],
      adType: "1",
      editId: "",
      chatHeight: 0
    });
  },
  afterRead(e) {
    let file = e.detail.file;
    console.log(file);
    let type = e.currentTarget.dataset.uptype;
    upload({ file, uploadType: type }).then(url => {
      let adPicList = this.data.adPicList
      adPicList.push({ url })
      this.setData({ adPicList });
    })
  },
  deleteFile(event) {
    let index = event.detail.index;
    let list = this.data.adPicList
    list.splice(index, 1);
    this.setData({
      adPicList: list
    })
  },
  // 广告type选项发生变化
  onAdTypeChange(event) {
    console.log(event.detail);
    this.setData({
      adType: event.detail
    })
  },
  // 获取列表数据
  getData() {
    queryADVByPage(Object.assign(this.data.pageOption, { Name: this.data.searchName })).then(res => {
      console.log(res);
      if (res.Data.ADVDtos.length > 0) {
        this.setData({
          adList: res.Data.ADVDtos,
        });
      }
      if (!JSON.stringify(res.Data.ADVDtos).includes(this.data.checkAdLink)) {
        this.setData({
          checkAdLink: ""
        })
      }
    })
  },

  // 删除广告链接
  handleRemove(e) {
    const Id = e.currentTarget.dataset.value;
    if (this.data.checkAdLink == Id) {
      Toast("选中状态下不可移除！");
      return
    }
    delADV({ Ids: [Id] }).then(() => {
      this.getData();
      if (this.data.checkAdLink == Id) {
        this.setData({
          checkAdLink: ""
        })
      }
    })
  },
  // 编辑广告链接
  handleEdit(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      isShowAddLink: true,
      adPicList: [{ url: value.CoverUrl }],
      adLink: value.ADVUrl,
      adType: String(value.ADVType),
      adSlogan: value.Name,
      editId: value.Id
    });
  },
  // 确认选择广告链接
  handleselectAd() {
    var pages = getCurrentPages()
    var prevPage = pages[pages.length - 2];
    const slAd: any = this.data.adList.filter((item: any) => item.Id == this.data.checkAdLink)[0];
    console.log(slAd);
    // if (slAd) {
    prevPage.setData({
      adValue: slAd ? slAd.ADVUrl : "",
      ADVId: slAd ? slAd.Id : ""
    });
    // }
    wx.navigateBack({
      delta: -1
    })
  },
  cancelSelectAd() {
    wx.navigateBack({
      delta: -1
    })
  },
  noop() { }

})